import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: () => import('@/layout/Index.vue'),
    redirect: '/cattle',
    meta: { requiresAuth: true },
    children: [
      {
        path: '/cattle',
        name: 'Cattle',
        component: () => import('@/views/cattle/Index.vue'),
        meta: { requiresAuth: true, title: '奶牛档案' }
      },
      {
        path: '/disease',
        name: 'Disease',
        component: () => import('@/views/disease/Index.vue'),
        meta: { requiresAuth: true, title: '疾病登记' }
      },
      {
        path: '/user',
        name: 'User',
        component: () => import('@/views/user/Index.vue'),
        meta: { requiresAuth: true, title: '用户管理', roles: ['admin'] }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  // 检查是否需要登录
  // if (to.meta.requiresAuth) {
  //   if (!userStore.token) {
  //     ElMessage.warning('请先登录')
  //     next('/login')
  //     return
  //   }
    
  //   // 检查角色权限
  //   if (to.meta.roles && !to.meta.roles.includes(userStore.role)) {
  //     ElMessage.error('无权限访问')
  //     next('/cattle')
  //     return
  //   }
  // }
  
  // 已登录用户访问登录页，跳转到首页
  if (to.path === '/login' && userStore.token) {
    next('/cattle')
    return
  }
  
  next()
})

export default router

